﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Management;

namespace Utils.Common
{
    public class LocalMachineHelper
    {


        /// <summary>  
        /// 取网卡信息  
        /// </summary>  
        /// <returns></returns>  
        public static List<NetAdapter> GetNetAdapterInfo()
        {
            List<NetAdapter> NetAdapterList = new List<NetAdapter>();


            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            if (adapters != null)
            {
                foreach (NetworkInterface ni in adapters)
                {
                    StringBuilder sb = new StringBuilder();
                    string fCardType = "未知网卡";
                    IPInterfaceProperties ips = ni.GetIPProperties();

                    PhysicalAddress pa = ni.GetPhysicalAddress();
                    if (pa == null) continue;
                    string pastr = pa.ToString();
                    if (pastr.Length < 7) continue;
                    if (pastr.Substring(0, 6) == "000000") continue;
                    if (ni.Name.ToLower().IndexOf("vmware") > -1) continue;
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + ni.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID       
                        // 如果前面有 PCI 就是本机的真实网卡      
                        // MediaSubType 为 01 则是常见网卡，02为无线网卡。      
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
                        if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
                            if (ni.NetworkInterfaceType.ToString().ToLower().IndexOf("wireless") == -1)
                                fCardType = "物理网卡";
                            else
                                fCardType = "无线网卡";
                        else if (fMediaSubType == 1 || fMediaSubType == 0)
                            fCardType = "虚拟网卡";
                        else if (fMediaSubType == 2 || ni.NetworkInterfaceType.ToString().ToLower().IndexOf("wireless") > -1)
                            fCardType = "无线网卡";
                        else if (fMediaSubType == 7)
                            fCardType = "蓝牙";
                    }
                    StringBuilder isb = new StringBuilder();
                    UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = ips.UnicastAddresses;
                    foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection)
                    {
                        if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                            isb.Append(string.Format("Ip Address: {0}", UnicastIPAddressInformation.Address) + "\r\n"); // Ip 地址      
                    }

                    IPAddressCollection ipc = ips.DnsAddresses;
                    if (ipc.Count > 0)
                    {
                        foreach (IPAddress ip in ipc)
                        {
                            isb.Append(string.Format("DNS服务器地址：{0}\r\n", ip));
                        }
                    }
                    string s = string.Format("{0}\r\n描述信息：{1}\r\n类型：{2}\r\n速度：{3} MB\r\nMac地址：{4}\r\n{5}", fCardType, ni.Name, ni.NetworkInterfaceType, ni.Speed / 1024 / 1024, ni.GetPhysicalAddress(), isb.ToString());
                    sb.Append(s + "\r\n");



                    NetAdapter netAdapter = new NetAdapter();
                    {
                        netAdapter.CardType = fCardType;
                        netAdapter.CardInfo = ni.Name;
                        netAdapter.NetworkInterfaceType = ni.NetworkInterfaceType.ToString();
                        netAdapter.MacAddress = ni.GetPhysicalAddress().ToString();
                        netAdapter.DetailInfo = sb.ToString();
                    }
                    NetAdapterList.Add(netAdapter);
                }
            }
            return NetAdapterList;
        }



        public static string GetHardDiskID()
        {
            string dardDiskID = String.Empty;

            dardDiskID = GetHardDiskID_01();
            if (string.IsNullOrEmpty(dardDiskID))
            {
                dardDiskID = GetHardDiskID_02();
            }
            if (string.IsNullOrEmpty(dardDiskID))
            {
                dardDiskID = GetHardDiskID_03();
            }

            return dardDiskID.Trim();
        }


        //第一種方式获取硬盘ID
        private static string GetHardDiskID_01()
        {
            string DiskID = "";
            try
            {
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["SerialNumber"].Value;
                    if (HDid != string.Empty && HDid != null)
                    {
                        break;
                    }
                }
                moc = null;
                mc = null;
                DiskID = HDid;
            }
            catch
            {
                DiskID = "";
            }
            return DiskID;
        }

        //第二種方式获取硬盘ID
        private static string GetHardDiskID_02()
        {
            string DiskID = "";
            try
            {

                String HDidi = string.Empty;
                ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc1 = cimobject1.GetInstances();
                foreach (ManagementObject mo in moc1)
                {
                    HDidi = (string)mo.Properties["SerialNumber"].Value;
                    if (HDidi != string.Empty && HDidi != null)
                    {
                        break;
                    }
                }
                cimobject1 = null;
                moc1 = null;
                DiskID = HDidi;
            }
            catch
            {
                DiskID = "";
            }
            return DiskID;
        }

        /// <summary>取第一块硬盘编号</summary>
        private static String GetHardDiskID_03()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                String strHardDiskID = null;
                foreach (ManagementObject mo in searcher.Get())
                {
                    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                return strHardDiskID;
            }
            catch
            {
                return "";
            }
        }//end


        /// <summary>
        /// 取机器名
        /// </summary>
        /// <returns></returns>
        public static string GethostName()
        {
            return System.Net.Dns.GetHostName();
        }

        /// <summary>
        /// 获取cpu序列号
        /// </summary>
        /// <returns></returns>
        public static string GetCPUSerialNumber()
        {
            string cpuSerialNumber = string.Empty;
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                cpuSerialNumber = mo["ProcessorId"].ToString();
                break;
            }
            mc.Dispose();
            moc.Dispose();
            return cpuSerialNumber;
        }





    }

    public class NetAdapter
    {
        /// <summary>
        /// 网卡类别
        /// </summary>
        public string CardType
        {
            get;
            set;

        }

        /// <summary>
        /// 描述
        /// </summary>
        public string CardInfo
        {
            get;
            set;

        }
        /// <summary>
        /// 网卡类型
        /// </summary>
        public string NetworkInterfaceType
        {
            get;
            set;

        }

        /// <summary>
        /// 物理地址
        /// </summary>
        public string MacAddress
        {
            get;
            set;
        }

        /// <summary>
        /// 详细
        /// </summary>
        public string DetailInfo
        {
            get;
            set;
        }

    }




 
}